﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI;
using System.Collections;
using Microsoft.Office.Server.UserProfiles;
using System.Web.Hosting;


namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class QatarID_VisaRenewal_Print : LayoutsPageBase
    {
        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string QatarIDRequestNo;
        public static string SourceLstName;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;

        public static string MainLstDetails;

        public static string lstGuid { get; set; }
        public string camlQry { get; set; }
        public static string Mode { get; set; }
        public static string submittedfor { get; set; }
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string refID;
        public static string TaskItemID;
        private static bool Submit = false;

        public static string DocStatus;

        private static SPListItemCollection oItemsColl = null;
        private static SPListItem oItems = null;

        public static string RequestType = null;

        private int isDuplicateNo;

        public static bool isDuplicateClassName = false;


        string[] buttonVisibilty = new string[5];

        #endregion

        public QatarID_VisaRenewal_Print()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Qatar ID Visa Renewal Forms";
            TaskLstName = "Qatar ID Visa Renewal Tasks";
            CmntsLstName = "Qatar ID Visa Renewal Comments";
            MainLstDetails = "Qatar ID Visa Renewal Details";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                Mode = Request.QueryString["Mode"];
                refID = Request.QueryString["RefID"]; // From Dashboard.
                TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);

                if (Mode == "Print" || Mode == "View")
                {
                    ReLoadDetails(); 
                }
                else
                {
                    pnlFullForm.Visible = false;
                    pnlAccessDenied.Visible = true;
                    lblAccessDeniedMsg.Visible = true;
                    lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                }
            }
        }

        /// <summary>
        /// Function to bind data after the Form gets submitted.
        /// </summary>
        /// <param name="SiteURL"></param>

        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite osite = new SPSite(SiteURL))
                    {
                        using (SPWeb oweb = osite.OpenWeb())
                        {

                            string RefNo = Convert.ToString(Request.Params["RefID"]);

                            camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + RefNo + "</Value></Eq></Where>";
                            SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                            if (lstDatas != null)
                            {
                                lblQIdReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                                dtReqDate.Text = Convert.ToDateTime(lstDatas["RequestDate"]).ToString("dd/MM/yyyy");
                                SPQuery oqry = new SPQuery();
                                oqry.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + RefNo + "</Value></Eq></Where>";

                                ReLoadQatarIDDetails(oweb, lblQIdReqNo.Text, oqry); // Expense List items
                                GetApprovedUsers(RefNo);

                            }
                        }
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        /// <summary>
        /// Edit the Qatar ID details in the GridView
        /// </summary>
        /// <param name="oweb"></param>
        /// <param name="RefNo"></param>
        /// <param name="oqry"></param>
        /// 
        public void ReLoadQatarIDDetails(SPWeb oweb, string RefNo, SPQuery oqry)
        {
            try
            {
                SPList QatarIDDetails = oweb.Lists.TryGetList(MainLstDetails);
                if (QatarIDDetails != null)
                {
                    SPListItemCollection oItemColl = QatarIDDetails.GetItems(oqry);
                    if (oItemColl.Count > 0)
                    {
                        fnShowGridDetails(oItemColl);
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal Form " + " :: " + "Parent" + " :: " + "ReLoadQatarIDDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion


        /// <summary>
        /// Edit Qatar ID details in GridView
        /// </summary>
        /// <param name="oitemcollDraw"></param>
        public void fnShowGridDetails(SPListItemCollection oItemsColl)
        {
            try
            {
                gvQatarID.DataSource = oItemsColl.GetDataTable();
                gvQatarID.DataBind();

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Qatar ID Visa Renewal form" + " :: " + "Parent" + " :: " + "Reject";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        private void GetApprovedUsers(string refNo)
        {
            SPListItemCollection oItemColl = null;
            string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
            oItemColl = obj.GetSPListItems(SiteURL, TaskLstName, camlQry);
            DataTable dt = new DataTable();
            // dt.Columns.Add("Approved By");
            DataRow dr;

            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    if (oItemColl.Count > 0)
                    {
                        foreach (SPListItem oItem in oItemColl)
                        {
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                            dt.Columns.Add(oItem["ID"].ToString());
                        }

                        dr = dt.NewRow();
                        int wfCnt = dt.Columns.Count;
                        int i = 0;
                        foreach (SPListItem oItem in oItemColl)
                        {
                            if (i < wfCnt)
                            {
                                SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, Convert.ToString(oItem["AssignedTo"]));
                                if (Convert.ToString(fldUser.LookupValue).Contains("\\"))
                                {
                                    string user = Convert.ToString(fldUser.LookupValue);
                                    string[] users = user.Split('\\');
                                    int arrLenth = users.Length;
                                    if (arrLenth > 0)
                                        dr[i] = users[1];
                                    else
                                        dr[i] = users[0];
                                }
                                i++;
                            }
                        }
                        dt.Rows.Add(dr);
                        i = 0;
                        dr = dt.NewRow();
                        while (i < wfCnt)
                        {
                            dr[i] = "Approved By";
                            i++;
                        }
                        dt.Rows.Add(dr);
                        gvApprovers.DataSource = dt;
                        gvApprovers.DataBind();
                        gvApprovers.HeaderRow.Visible = false;
                    }

                }

            }

        }
    }
}
